package com.chao.juc.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author : Rookie
 * @description :
 * @date : 2022/1/9
 */
public class Ticket {

    public int num = 50;

    Lock lock = new ReentrantLock();

    //使用synchronized
//    public synchronized void sale(){
//        if (num > 0){
//            System.out.println(Thread.currentThread().getName() + "卖出了第" + num-- + "张票,还剩" + num + "张");
//        }
//    }

    //使用Lock
    public void sale(){
        //先加锁
        lock.lock();
        try {
            if (num > 0){
                System.out.println(Thread.currentThread().getName() + "卖出了第" + num-- + "张票,还剩" + num + "张");
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //必须解锁
            lock.unlock();
        }
    }
}
